import { InjectionToken, Injector } from '@angular/core';
import { DA_SERVICE_TOKEN, JWTTokenModel, mergeConfig, SimpleTokenModel } from '@delon/auth';
import { AlainConfigService } from '@delon/util/config';

const WINDOW = new InjectionToken<any>('Window');

export function CheckSimple(model: SimpleTokenModel): boolean {
  return model != null && typeof model.token === 'string' && model.token.length > 0;
}

export function CheckJwt(model: JWTTokenModel, offset: number): boolean {
  // token不为空且存在且未过期  返回true  否则false
  return model != null && model.token != null && !model.isExpired(offset);
}

export function LocalChangeToken(injector: Injector): Promise<void> {
  return new Promise<void>(resolve => {
    const tokenSrv = injector.get(DA_SERVICE_TOKEN);
    const model = tokenSrv.get<JWTTokenModel>(JWTTokenModel);
    const options = mergeConfig(injector.get(AlainConfigService));

    const hasToken = model != null && model.token != null && !model.isExpired(options.token_exp_offset);
    // 如果token过期，就看有没有可刷新的token
    if (!hasToken && !!model['refreshToken']) {
      // 将刷新token替换为正常token
      tokenSrv.set({
        token: model['refreshToken'],
        expired: new Date().valueOf() + options.token_exp_offset!,
        time: Date.parse(new Date().toString()) / 1000,
        refreshToken: model['refreshToken']
      });
    }
    resolve();
  });
}
